package com.yt.demo.realm;

import com.yt.demo.dao.UserDao;
import com.yt.demo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserDao userDao;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("==========自定义的授权方法==========");
        System.out.println("执行。。。。 。"+principalCollection.getPrimaryPrincipal());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRole("admin");
        info.addStringPermission("user:select");
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        String username=authenticationToken.getPrincipal().toString();
        System.out.println("myrealm.info ==> username:"+username);
        User user=userDao.getUserByUsername(username);
        log.info("myrealm 中查到数据库中的user"+ user);

        AuthenticationInfo info=null;
        if(user !=null){
            //加盐迭代3次后的密码
            info=new SimpleAuthenticationInfo(
                    user//authenticationToken.getPrincipal()
                    ,user.getPassword()
                    , ByteSource.Util.bytes("salt"),
                    authenticationToken.getPrincipal().toString());
        }
        return info;
    }
}
